﻿using ARPaintServer.Model.Artwork;
using ARPaintServer.Model.OTD;

namespace ARPaintServer.Services
{
	public class ArtworkService:IArtworkService
	{
		private readonly DataContext _context;

		public ArtworkService(DataContext context)
		{
			_context = context;
		}

		public async Task<Artwork> GetArtworkFromIDAsync(string id)
		{
			var result=await (from artwork in _context.Artworks
					   where artwork.ArtworkID == id
					   select artwork).FirstAsync();
			return result; 
		}

		public async Task SaveArtworkAsync(Artwork artwork)
		{
			await _context.Artworks.AddAsync(artwork);
			await _context.SaveChangesAsync();
			//Console.WriteLine($"保存了{artwork.Author}上传的{artwork.Name}");
		}

		public async Task<List<ArtworkInfo>> GetArtworkInfoAsync(int amount)
		{
			var artworks=await _context.Artworks.Take(amount).ToListAsync();
			var artworkInfos = (from artwork in artworks
							   select GetArtworkInfoFromArtwork(artwork)).ToList();
			return artworkInfos;
		}

		public async Task<List<ArtworkInfo>> GetArtworkInfoFromAuthorAsync(string author,int amount)
		{
			var artworks= await (from artwork in _context.Artworks
						 where artwork.Author== author
						 select artwork).Take(amount).ToListAsync();
			var artworkInfos = (from artwork in artworks
								select GetArtworkInfoFromArtwork(artwork)).ToList();
			return artworkInfos;
		}
	
		private ArtworkInfo GetArtworkInfoFromArtwork(Artwork artwork)
		{
			ArtworkInfo artworkInfo = new()
			{
				ArtworkID = artwork.ArtworkID,
				Author = artwork.Author,
				//CreateTime = artwork.CreateTime,
				Description = artwork.Description,
				Name = artwork.Name,
				Theme = artwork.Theme,
				Version = artwork.Version,
				Cover=artwork.Cover,
			};
			return artworkInfo; 
		}
	}
}
